package com.ruoyi.pay.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.pay.domain.WxpayConfig;
import com.ruoyi.pay.mapper.WxpayConfigMapper;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.service.partnerpayments.h5.H5Service;
import com.wechat.pay.java.service.partnerpayments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;

/**
 * @author caozhen
 * @ClassName WxPayAutoCertificateConfig
 * @description: 微信支付证书自动更新配置
 * @date 2024年01月03日
 * @version: 1.0
 */
@Configuration
public class WxPayAutoCertificateConfig {

    @Resource
    private WxpayConfigMapper wxpayConfigMapper;

    @Bean
    @Primary
    public Config config() {
        QueryWrapper<WxpayConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("is_check", 0);
        WxpayConfig wxPayConfig = wxpayConfigMapper.selectOne(wrapper);
        if (wxPayConfig == null) {
            throw new RuntimeException("未找到微信支付配置信息");
        }
        // 使用自动更新平台证书的RSA配置
        return new RSAPublicKeyConfig.Builder()
                .merchantId(wxPayConfig.getMerchantId())
                .privateKey(wxPayConfig.getPrivateKey())
                .publicKey(wxPayConfig.getPublicKey())
                .publicKeyId(wxPayConfig.getPublicKeyId())
                .merchantSerialNumber(wxPayConfig.getMerchantSerialNumber())
                .apiV3Key(wxPayConfig.getApiV3key())
                .build();
    }

    @Bean
    @Primary
    public H5Service h5Service(Config config) {
        return new H5Service.Builder()
                .config(config)
                .build();
    }

    @Bean
    @Primary
    public JsapiService jsapiService(Config config) {
        return new JsapiService.Builder()
                .config(config)
                .build();
    }

    @Bean
    @Primary
    public NativePayService nativePayService(Config config) {
        return new NativePayService.Builder()
                .config(config)
                .build();
    }

    @Bean
    @Primary
    public NotificationParser notificationParser(Config config) {
        return new NotificationParser((NotificationConfig) config);
    }
}
